package org.dftproject.genesis.ui.figures;

import java.util.List;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;

public class UniformSizeContainer extends Figure {

	private final UniformSizeGroup group;
	private final boolean stretch;

	public UniformSizeContainer(final IFigure figure, UniformSizeGroup group) {
		this(figure, group, true);
	}

	public UniformSizeContainer(final IFigure figure, UniformSizeGroup group, boolean stretch) {
		this.group = group;
		this.setLayoutManager(new UniformSizeLayout());
		this.stretch = stretch;
		add(figure);
		group.add(figure);
	}

	protected class UniformSizeLayout extends StackLayout {

		@Override
		protected Dimension calculateMinimumSize(IFigure figure, int wHint, int hHint) {
			return group.getMinimumSize(wHint, hHint);
		}

		@Override
		protected Dimension calculatePreferredSize(IFigure figure, int wHint, int hHint) {
			return group.getPreferredSize(wHint, hHint);
		}

		@SuppressWarnings("unchecked")
		@Override
		public void layout(IFigure figure) {
			Rectangle clientArea = figure.getClientArea();
			
			for (IFigure child : (List<IFigure>) figure.getChildren()) {
				child.setBounds(stretch ? clientArea : clientArea.getCopy().setSize(child.getPreferredSize(clientArea.width, clientArea.height)));
			}
		}

	}

}
